package com.google.code.coma.gui.worker;

import com.google.code.coma.worker.Worker;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author Dominik Strasser, dominikstr@gmail.com
 */
public class WorkerManager {

    private static final Log log = LogFactory.getLog(WorkerManager.class);

    public enum Mode {
        SPACE, RMI
    }

    public enum WorkerType {
        PRODUCTION, ASSEMBLY, TESTER, LOGISTICS
    }

    private static Properties config;

    private static Map<String, Worker> activeWorkers = new HashMap<String, Worker>();

    static {
        InputStream in = WorkerManager.class.getResourceAsStream("/workers.properties");
        config = new Properties();
        try {
            config.load(in);
        } catch (IOException e) {
            log.error("unable to load configuration", e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                //is okay
            }
        }
    }

    public static String createWorker(WorkerType worker, Mode mode, Object... params) {
        Class[] argumentTypes = new Class[params.length];
        for (int i = 0; i < params.length; i++) {
            argumentTypes[i] = params[i].getClass();
        }

        return createWorker(worker, mode, argumentTypes, params);
    }

    public static String createWorker(WorkerType worker, Mode mode, Class[] argumentTypes, Object... params) {
        String className = config.getProperty(mode + "_" + worker);
        try {
            Worker workerInstance = (Worker) Class.forName(className).getConstructor(argumentTypes).newInstance(params);
            workerInstance.startWork();
            activeWorkers.put(workerInstance.getWorkerId(), workerInstance);
            if (log.isInfoEnabled()) {
                log.info("Created worker with id " + workerInstance.getWorkerId());
            }
            return workerInstance.getWorkerId();
        } catch (Exception e) {
            log.error("Unable to create worker", e);
            throw new RuntimeException("Unable to create worker");
        }
    }

    public static void stopWorker(String id) {
        if (activeWorkers.containsKey(id)) {
            Worker w = activeWorkers.remove(id);
            w.stopWork();
            if (log.isInfoEnabled()) {
                log.info("Stopped worker " + id);
            }
        }
    }

    public static Map<String, Worker> getWorkers() {
        return Collections.unmodifiableMap(activeWorkers);
    }

    public static void stop() {
        for (Worker w : activeWorkers.values()) {
            w.stopWork();
        }
    }
}
